package com.ccc3gc.listener;

import com.ccc3gc.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.List;

@WebListener
public class OnlineUserListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    ServletContext application;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        List<User> users = new ArrayList<User>();
        application = sce.getServletContext();
        application.setAttribute("users", users);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        User user = (User) session.getAttribute("user");
        List<User> users = (List<User>) application.getAttribute("users");
        users.add(user);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {


    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        User user = (User) session.getAttribute("user");
        List<User> users = (List<User>) application.getAttribute("users");
        users.remove(user);
    }
}
